<?php
// +----------------------------------------------------------------------
// | makePHP 
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://makephp.org All rights reserved.
// +----------------------------------------------------------------------
// | Licensed BSD.(http://www.make.org/BSD-license.txt)
// +----------------------------------------------------------------------
// | Author: 叁石(sanshi) <sanshi0815@tom.com>
// | Author: 白家昌<baijc2004cn@126.com>
// +----------------------------------------------------------------------

/**
 *pdo 数据库连接类
 * @name    PdoMysql
 * @see         
 * @version	1.0.0 
 * @author	sanshi
 */
class PdoMysql      
{      
    //读数据库句柄      
    private $select_db;      
    //写数据库句柄      
    private $update_db;      
    //配置数据信息数组      
    private $con_str = array();      
    //数据读写方式      
    private $db_type=array('read','write');
	private $read_db;
	private $write_db;
    //所有的执行信息      
    private $dubug_msg = array();      
    //排序默认采用方式      
    private $taxis = "DESC";      
    //是否显示调试信息      
    public  $debug = false;      
    //是否采用长连接 true 为采用      
    private $p_con = false;      
          
    function __construct()      
    {      
        $this->PdoMysql();      
    }      
    /**    
     * @abstract 初始化    
     * @access public    
     * @return void    
     * */     
    function PdoMysql()      
    {      
        global $mysql_con_arr; 
		//print_r($mysql_con_arr);exit();
        foreach ($mysql_con_arr as $key=>$db_conf)      
        {      
            if(in_array($key,$this->db_type))      
            {      
                $db_conf['db_port'] = isset($db_conf['db_port']) ? $db_conf['db_port'] : 3306;      
                $this->con_str[$key]['dns'] = "mysql:dbname={$db_conf['db_name']};host={$db_conf['db_host']};port={$db_conf['db_port']}";      
                //echo $this->con_str[$key]['dns'];exit();
				$this->con_str[$key]['user'] = $db_conf['db_user'];      
                $this->con_str[$key]['pwd'] = $db_conf['db_pwd'];      
                $this->con_str[$key]['charset'] = $db_conf['db_charset'];      
            }      
        }      
    }      
    /**    
     * @abstract 获取数据连接资源    
     * @access private    
     * @param string $db_type  数据库连接类型    
     * @return object          数据库连接资源    
     * */     
    function __connect($db_type)      
    {      
        if(!isset($this->con_str[$db_type]))      
                $db_type = $this->db_type[0];      
        $db_str = "{$db_type}_db";      
        if(!is_object($this->$db_str))      
        {      
            $con = $this->con_str[$db_type];      
            try{      
                $this->$db_str = $this->p_con ?       
                    new PDO($con['dns'], $con['user'], $con['pwd'],array(PDO::ATTR_PERSISTENT=>true)):new PDO($con['dns'], $con['user'], $con['pwd']);  
                $sql = "SET NAMES '{$con['charset']}' ";      
                $this->query($sql,$db_type);
            }catch (PDOException $e){      
                $this->__setDebug($e->getMessage());      
                $this->showBug();      
                //die('系统暂时不支持PDO,详细错误:' . $e->getMessage());
				jumpError(-1001);
                return false;      
            }      
        }      
        return $this->$db_str;      
    }      
    /**    
     * @abstract 执行插入语句    
     * @access public    
     * @param string    $table      表名    
     * @param array     $values     字段与值对应的数组    
     * @param bool      $is_result      是否返回最后插入的id值    
     * @return   如果设置$is_result为true返回插入id 否则返回bool值    
     * */     
    function insert($table, $values,$is_result=true)      
    {      
        $db = $this->__connect($this->db_type[1]);      
		$sql = $this->__createSql($values);
        $res =$db->prepare(" INSERT INTO {$table} SET {$sql}");
        $this->__setDebug(" INSERT INTO {$table} SET {$sql}");  

        $this->showBug(); 
        if(!$res->execute())      
        {      
            $this->__setDebug($res->errorInfo());      
            return -1002;      
        } 
        return $is_result ? $db->lastInsertID() : -1002;      
    }      
    /**    
     * @abstract     
     * @access public    
     * @param string    $table    
     * @param array     $values    
     * @param string    $where    
     * @param bool      $is_result    
     * @return 如果 $is_result为true的话，返回影响的条数 否则返回bool值    
     * */     
    function update($table='',$values='',$where=1,$is_result=true)      
    {      
        $db = $this->__connect($this->db_type[1]);      
        $sql = $this->__createSql($values);      
        $res = $db->prepare(" UPDATE {$table} SET {$sql} WHERE {$where} ");      
        $this->__setDebug(" UPDATE {$table} SET {$sql} WHERE {$where} ");      
        $this->showBug();      
        if(!$res->execute())      
        {      
            $this->__setDebug($res->errorInfo());      
            return -1003;      
        }      
        return $is_result ? $res->rowCount() : -1003;      
    }      
    /**    
     * @abstract  数据库查询操作    
     * @access public    
     * @param string    $sql        主sql    
     * @param string    $col        排序字段    
     * @param int       $numrows    获取记录条数    
     * @param int       $offset     获取记录开始条数    
     * @return array    返回结果数组，如果为空，查询失败    
     * */     
    function select($sql,$col='',$numrows=-1,$offset=-1)      
    {      
        $db = $this->__connect($this->db_type[0]);      
        $sql=empty($col)? $sql : $sql." ORDER BY ".$col." ".$this->taxis ;
        $sql = $numrows > 0 ? $sql.=" LIMIT ".( $offset < 0 ? 0 : $offset ).", {$numrows} " : $sql;
        $res = $this->query($sql);      
        if(!is_object($res)&&$res<0)      
        {      
            $this->__setDebug(@$res->errorInfo());      
            return -1006;      
        }      
        return $res->fetchAll(PDO::FETCH_ASSOC);      
    }      
    /**    
     * @abstract 数据库删除方法    
     * @access public    
     * @param string    $table      表名    
     * @param string    $where      删除条件    
     * @param bool      $is_result  是否返回影响条数    
     * @return 如果 $is_result为true的话，返回影响的条数 否则返回bool值    
     * */     
    function delete($table,$where='',$is_result=true)      
    {      
        $db = $this->__connect($this->db_type[1]);     
        $res = $db->prepare(" DELETE FROM {$table}  WHERE {$where} ");      
        $this->__setDebug(" DELETE FROM {$table}  WHERE {$where} ");      
        $this->showBug();      
        if(!$res->execute())      
        {      
            $this->__setDebug($res->errorInfo());      
            return -1004;      
        }      
        return $is_result ? $res->rowCount() : -1004;      
    }      


    /**    
     * @abstract 取得符合条件的记录条数    
     * @access public    
     * @param string    $table  表名    
     * @param string    $where  条件    
     * @return int  返回记录条数    
     * */     
    function getSumNumber($table, $where='1')      
    {      
        $db = $this->__connect($this->db_type[0]);      
        $res = $db->prepare("SELECT COUNT(1) AS CNT FROM {$table} WHERE {$where}");
        $this->__setDebug("SELECT COUNT(1) AS CNT FROM {$table} WHERE {$where}");      
        $this->showBug();      
        if(!$res->execute())      
        {      
            $this->__setDebug($res->errorInfo());      
            return -1007;      
        }      
        $row = $res->fetchAll();      
        return $row[0]['CNT'];      
    }      
    /**    
     * @abstract 执行非常规sql语句    
     * @access public    
     * @param string $sql     执行语句    
     * @param string $db_type 数据库类型    
     * @return object         数据库执行结果    
     * */     
    function query($sql,$db_type="write")      
    {      
        if(!in_array($db_type,$this->db_type))      
            $db_type = $this->db_type[0];      
        $db = $this->__connect($db_type);      
        $this->__setDebug($sql);      
        $this->showBug();      
        $res = $db->query($sql);
		return $res ? $res : -1005;
    }   

    /**    
     * @abstract 执行插入自增表语句    
     * @access public    
     * @param string    $table      表名    
     * @return   返回插入id   
     * */     
    public function insertAuto($table)
    {
        $db = $this->__connect($this->db_type[1]);
        $res = $db->prepare(" INSERT INTO {$table} () VALUES ()");
        $this->__setDebug(" INSERT INTO {$table} () VALUES ()");
        $this->showBug();
        if(!$res->execute())
        {
            $this->__setDebug($res->errorInfo());
            return -1002;
        }
        return $db->lastInsertID();
    }
	
    /**    
     * @abstract 获取数据库连接句柄    
     * @access public    
     * @param string $db_type   数据库连接类型    
     * @return object   数据库连接句柄    
     * */     
    function getDB($db_type="write")      
    {      
        if(!in_array($db_type,$this->db_type))      
            $db_type = $this->db_type[0];      
        $db = $this->__connect($db_type);      
        return $db;      
    }      
    /**    
     * @abstract 建立sql 语句    
     * @access privait    
     * */     
    function __createSql($value)      
    {      
        if(!is_array($value))      
        {      
            $this->__setDebug("sql语句建立失败");      
            exit();      
        }      
        $temp=array();      
        foreach ($value as $key=>$value)      
        {      
            $temp[] = is_int($value) ? "`" . $key . "` = " . $value ." " :       
                "`" . $key . "` = \"" . addslashes($value) . "\"";  
        }      
        $sql=implode(',',$temp);      
        return $sql;      
    }      
    /**    
     * @abstract 设置数据库排序方式    
     * @access public    
     * @param  string   $taxis  数据库派讯方式，默认为asc，该类默认为 desc    
     * @return void    
     * */     
    function setOrderBy($taxis="ASC")      
    {      
        $this->taxis = $taxis;      
    }      
    /**    
     * @abstract 设置bug信息    
     * @access private    
     * @param string    $msg    调试信息    
     * @return void    
     * */     
    function __setDebug($msg)      
    {      
        $msg = is_array($msg) ? implode(',',$msg) : $msg;      
        $this->dubug_msg[] = date('Y-m-d H:i:s')." {$msg}";      
    }      
    /**    
     * @abstract 获取调试信息    
     * @access public    
     * @return array    调试信息    
     * */     
    function getDebug()      
    {      
        return $this->dubug_msg;      
    }
	function getDebugMsg()
	{
		return $this->dubug_msg;
	}
    /**    
     * @abstract 输出所有的调试信息，受全局debug控制    
     * @access public    
     * */     
    function showBug()      
    {      
        if($this->debug)      
        {      
            echo "<br/><hr/>";      
            print_r($this->getDebug());      
            echo "<br/><hr/>";      
        }      
    }      
}    
/*
$db = new PdoMysql();   
print_r($db);   
print_r($db->getSumNumber("eos_adminers"));   
print_r($db->insert("eos_adminers",array('id'=>'',"user_name"=>'sanshi'.time())));   
print_r($db->update("eos_adminers",array("user_name"=>'sanshi12334'),"id=2"));   
print_r($db->select("SELECT * FROM eos_adminers",'id'));   
print_r($db->delete("eos_adminers","id=2"));   
print_r($db->getDebug());  
*/
?>